#include <REGX52.H>
#include <Delay.h>
#include <Timer0.h>
#include <UART.h>
#include <OLED.h>

sbit ALE=P3^2;
sbit ST=P2^6;
sbit EOC=P2^5;
sbit ADCLK=P2^2;
sbit OE=P2^3;

sbit ADDA=P1^6;
sbit ADDB=P1^7;
sbit ADDC=P2^7;

sbit DB0=P3^7;
sbit DB1=P2^0;
sbit DB2=P2^1;
sbit DB3=P2^4;
sbit DB4=P3^6;
sbit DB5=P3^5;
sbit DB6=P3^4;
sbit DB7=P3^3;

unsigned int numm[8]={000,000,000,000,000,000,000,000};

int hang (int nn)
{
	int out;
	if(nn<2)out=0;
	else if(nn<4) out=2;
	else if(nn<6) out=4;
	else out=6;
	return out;
}

void hc138(unsigned char dd)
{
	switch(dd)
	{
		case 0:ADDA=0;ADDB=0;ADDC=0;break;
		case 1:ADDA=1;ADDB=0;ADDC=0;break;
		case 2:ADDA=0;ADDB=1;ADDC=0;break;
		case 3:ADDA=1;ADDB=1;ADDC=0;break;
		case 4:ADDA=0;ADDB=0;ADDC=1;break;
		case 5:ADDA=1;ADDB=0;ADDC=1;break;
		case 6:ADDA=0;ADDB=1;ADDC=1;break;
		case 7:ADDA=1;ADDB=1;ADDC=1;break;
	}
}

void Number_Show(unsigned char location,number)
{
  unsigned char Array[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
	P0=0x00;
	switch(location)
	{
		case 0:P1_0=0,P1_1=1,P1_2=1,P1_3=1;break;
		case 1:P1_0=1,P1_1=0,P1_2=1,P1_3=1;break;
		case 2:P1_0=1,P1_1=1,P1_2=0,P1_3=1;break;
		case 3:P1_0=1,P1_1=1,P1_2=1,P1_3=0;break;
	}
	P0=Array[number];
}

void main()
{

	Timer0Init();
	UART_Init();
	OLED_Write_Init();
	ADCLK=0;
	while(1)
	{
		
		unsigned char i,result=0x00;
		for(i=0;i<8;i++)
		{
   		OE=0;
		  ST=0;ALE=0;
			hc138(i);
			ST=1;ALE=1;
			Delay(5);			
			ST=0;ALE=0;
			while(EOC==0);
		  OE=1;
      numm[i]=(((int)(DB0)*1+(int)(DB1)*2+(int)(DB2)*4+(int)(DB3)*8
				+(int)(DB4)*16+(int)(DB5)*32+(int)(DB6)*64+(int)(DB7)*128)*1.9608);	//
		}
			for(i=0;i<8;i++)
		{
			OLED_Display(hang(i),0+(i%2)*64,2,8,numm[i]/100%10);
			OLED_Display(hang(i),8+(i%2)*64,2,8,10);			
			OLED_Display(hang(i),16+(i%2)*64,2,8,numm[i]/10%10);
			OLED_Display(hang(i),24+(i%2)*64,2,8,numm[i]/1%10);			
		}
		
	}
}

void Timer0_Routine() interrupt 1
{
	ADCLK=!ADCLK;
}

void UART_Routine() interrupt 4
{
	unsigned char i;
	if(RI==1)
	{
		for(i=0;i<8;i++)
		{
		UART_SendByte('A');
		UART_SendByte('D');
		UART_SendByte(i+48);
		UART_SendByte('=');
		UART_SendByte((numm[i]/100%10)+48);
		UART_SendByte('.');
		UART_SendByte((numm[i]/10%10)+48);
		UART_SendByte((numm[i]/1%10)+48);
		UART_SendByte(' ');
		}
		RI=0;
	}
}
